from typing import Optional, List
from fastapi import APIRouter, Depends, Response
from sqlalchemy.orm import Session
from db import get_db, crud
from schemas.delivery_person import DeliveryPersonPagination, DeliveryPersonModel, \
    UpdateDeliveryPersonRequest, CreateDeliveryPersonRequest
from schemas.users import UserModel
from users.users import verify_token
from datetime import datetime

router = APIRouter(prefix="/delivery-person", tags=["配送员管理"])


@router.post("", response_model=DeliveryPersonModel, response_model_exclude_none=True)
def create(data: CreateDeliveryPersonRequest, user: UserModel = Depends(verify_token), db: Session = Depends(get_db)):
    data.created_on = datetime.now()
    data.created_by = user.id
    return crud.DeliveryPerson.create(db, data)


@router.get("", dependencies=[Depends(verify_token)],
            response_model=DeliveryPersonPagination,
            response_model_exclude_none=True)
def get_pagination(page: int, page_size: int, kw: Optional[str] = None, db: Session = Depends(get_db)):
    total, data = crud.DeliveryPerson.gets(db, page - 1, page_size, kw)
    return DeliveryPersonPagination(
        page=page,
        page_size=page_size,
        total=total,
        data=data
    )


@router.get("/all", response_model=List[DeliveryPersonModel], response_model_exclude_none=True)
def get_all(db: Session = Depends(get_db)):
    return crud.DeliveryPerson.get_all(db)


@router.put("", response_model_exclude_none=True)
def update(data: UpdateDeliveryPersonRequest,
           user: UserModel = Depends(verify_token),
           db: Session = Depends(get_db)):
    data.updated_on = datetime.now()
    data.updated_by = user.id
    crud.DeliveryPerson.update(db, data)

    return Response()


@router.delete("/{item_id}", dependencies=[Depends(verify_token)], response_model_exclude_none=True)
def delete(item_id: int, db: Session = Depends(get_db)):
    crud.DeliveryPerson.delete(db, item_id)
    return Response()
